import java.util.Deque;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;

class MySolution {
    public boolean isValid(String s) {
        if (s.length() % 2 != 0) {
            return false;
        }

        Map<Character, Character> pairs = new HashMap<Character, Character>() {{
            put('(', ')');
            put('[', ']');
            put('{', '}');
        }};
        Deque<Character> stack = new LinkedList<Character>();
        for (int i = 0; i < s.length(); i++) {
            if (pairs.containsKey(s.charAt(i))) {
                stack.push(s.charAt(i));
            } else {
                if (stack.isEmpty() || pairs.get(stack.peek()) != s.charAt(i)) {
                    return false;
                }
                stack.pop();
            }
        }
        return stack.isEmpty();
    }
}



















public class Solution {
    public boolean isValid(String s) {
        int n = s.length();
        // 先判断字符串个数，如果为单数，则必然无效
        if (n % 2 == 1) {
            return false;
        }

        Map<Character, Character> pairs = new HashMap<Character, Character>() {{
            put(')', '(');
            put(']', '[');
            put('}', '{');
        }};
        Deque<Character> stack = new LinkedList<Character>();
        for (int i = 0; i < n; i++) {
            char ch = s.charAt(i);

            // 判断是左括号还是右括号
            if (pairs.containsKey(ch)) {
                // 判断为右括号，进行第二次判断
                if (stack.isEmpty() || stack.peek() != pairs.get(ch)) {
                    // 如果栈为空，说明无左括号可以匹配，判定无效字符串
                    // 如果栈中左括号与之不匹配，判定无效字符串
                    return false;
                }
                stack.pop();
            } else {
                // 判断为左括号，推入栈
                stack.push(ch);
            }
        }
        return stack.isEmpty();
    }
}
